var pc;


function notIeGetIp() {
  var RTCPeerConnection = /*window.RTCPeerConnection ||62616964757a686964616fe4b893e5b19e31333365663465*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

  if (RTCPeerConnection) (function () {
    var rtc = new RTCPeerConnection({ iceServers: [] });
    if (1 || window.mozRTCPeerConnection) {      // FF [and now Chrome!] needs a channel/stream to proceed
      rtc.createDataChannel('', { reliable: false });
    };

    rtc.onicecandidate = function (evt) {
      // convert the candidate to SDP so we can run it through our general parser
      // see https://twitter.com/lancestout/status/525796175425720320 for details
      if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
    };
    rtc.createOffer(function (offerDesc) {
      grepSDP(offerDesc.sdp);
      rtc.setLocalDescription(offerDesc);
    }, function (e) { console.warn("offer failed", e); });


    var addrs = Object.create(null);
    addrs["0.0.0.0"] = false;
    function updateDisplay(newAddr) {
      if (newAddr in addrs) return;
      else addrs[newAddr] = true;
      var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
      window['netIp'] = displayAddrs.join(" or perhaps ") || "1.1.1.1";
    }

    function grepSDP(sdp) {
      var hosts = [];
      sdp.split('\r\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39
        if (~line.indexOf("a=candidate")) {     // http://tools.ietf.org/html/rfc4566#section-5.13
          var parts = line.split(' '),        // http://tools.ietf.org/html/rfc5245#section-15.1
            addr = parts[4],
            type = parts[7];
          if (type === 'host') updateDisplay(addr);
        } else if (~line.indexOf("c=")) {       // http://tools.ietf.org/html/rfc4566#section-5.7
          var parts = line.split(' '),
            addr = parts[2];
          updateDisplay(addr);
        }
      });
    }
  })();
}

function getIPs(callback) {
  var ip_dups = {};
  var RTCPeerConnection = window.RTCPeerConnection
    || window.mozRTCPeerConnection
    || window.webkitRTCPeerConnection;

  if (RTCPeerConnection) log('RTCPeerConnection != null');
  if (!RTCPeerConnection) {
    var iframe = document.createElement('iframe');
    iframe.sandbox = 'allow-same-origin';
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    var win = iframe.contentWindow;
    window.RTCPeerConnection = win.RTCPeerConnection;
    window.mozRTCPeerConnection = win.mozRTCPeerConnection;
    window.webkitRTCPeerConnection = win.webkitRTCPeerConnection;
    RTCPeerConnection = window.RTCPeerConnection
      || window.mozRTCPeerConnection
      || window.webkitRTCPeerConnection;
  }

  var mediaConstraints = {
    optional: [{RtpDataChannels: true}]
  };
  var servers = undefined;

  if (window.webkitRTCPeerConnection)
    servers = {iceServers: [{urls: 'stun:stun.l.google.com:19302?transport=udp'}]};

  pc = new RTCPeerConnection(servers, mediaConstraints);
  pc.onicecandidate = function (ice) {
    try {
      if (ice.candidate) {
        var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
        var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];
        if (ip_dups[ip_addr] === undefined)
          callback(ip_addr);
        window['publicIp'] = ip_addr || '0.0.0.0';
        ip_dups[ip_addr] = true;
      } else {
        var sdp = ice.target.localDescription.sdp;
        var sdps = sdp.split('\n');
        for (var i = 0; i < sdps.length; i++) {
          if (sdps[i].indexOf('c=IN') >= 0) {
            callback(sdps[i].split(' ')[2]);
          }
        }
      }
    } catch (e) {
    }
  };

  pc.createDataChannel('');
  pc.createOffer({}).then(function (offer) {
    log('----create offer ----');
    return pc.setLocalDescription(offer);
  }).then(function () {
    log('setLocalDescription ok');
  });

}


function getUrlParameter(name) {
  name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  var results = regex.exec(location.search);
  return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

function ready() {
  console.log(window.__wxjs_environment === 'miniprogram'); // true
}

if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) {
  document.addEventListener('WeixinJSBridgeReady', ready, false);
} else {
  ready();
}

function log(txt) {
  // console.log(txt)
  //document.getElementById('ipip').innerHTML += txt + '<br/>'
}

getIPs(function (ip) {
  // wx.miniProgram.navigateTo({url: getUrlParameter('navTo') + ip})
  // wx.miniProgram.postMessage({data: 'foo'})

  // console.log(ip);

  // wx.miniProgram.postMessage({data: ip});
  // wx.miniProgram.navigateBack({delta: 1});


});

notIeGetIp();
// getIPs(function (ip){});
